/*
 * @description: 工具解析函数
 * @Date: 2023-03-21 15:28:49
 * @example: 
 * @params: 
 */
function base64ToByteArray(base64String) {
  var binaryString = atob(base64String);
  var byteArray = new Uint8Array(binaryString.length);
  for (var i = 0; i < binaryString.length; i++) {
    byteArray[i] = binaryString.charCodeAt(i);
  }
  return byteArray;
}
function readUInt16LE(bytes) {
  var value = (bytes[1] << 8) + bytes[0];
  console.log("readUInt16LE", value & 0xffff);
  return value & 0xffff;
}

function readInt16LE(bytes) {
  var ref = readUInt16LE(bytes);
  console.log("readInt16LE", ref > 0x7fff ? ref - 0x10000 : ref);
  return ref > 0x7fff ? ref - 0x10000 : ref;
}
/**
 * @param {*} bytes 
 * @returns 
 */
function Decode(bytes) {
  var decoded = {};
  for (let i = 0; i < bytes.length; i++) {
    var channel_id = bytes[i++];
    var channel_type = bytes[i++];
    // BATTERY
    if (channel_id === 1 && channel_type === 117) {
      decoded.battery = bytes[i];
      i += 1;
    }
    // HUMIDITY
    else if (channel_id === 4 && channel_type === 104) {
      decoded.humidity = bytes[i] * 0.5;
      i += 1;
    }
    // TEMPERATURE
    else if (channel_id === 3 && channel_type === 103) {
      // ℃
      decoded.temperature = Number((bytes.slice(i, i + 2)[0] * 0.1).toFixed(1));
      i += 1;
    }
    // DEVICE STATUS 
    else if (bytes[3] === 255 && bytes[4] === 2) {
      // 上报周期
      decoded.status = true;
      decoded.step = bytes[5];
    }
    // WATER LEAK
    if (bytes[bytes.length - 3] === 5) {
      decoded.waterLeak = bytes[bytes.length - 1] === 0 ? "normal" : "leak";
    }

  }
  return decoded;
}

module.exports = {
    base64ToByteArray,
    Decode
}